import re
import json
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.util import check_tid, assert_result_dict, change_user_account_status, get_sql_info
from frame_work.logger import Logger
from frame_work.login import PcLogin
from frame_work import menu_list
from requests_toolbelt import MultipartEncoder
from frame_work.setting import image_Path
from frame_work.excel import get_all_data

logger = Logger(__name__).get_logger()


# 提交申诉
class SubmitSS(object):

    def __init__(self, tid):
        self.tid = tid
        self.session = ''
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    @staticmethod
    def get_user_data(nums):
        """
        批量读取/data/buyer_data.xlsx试客账户，达到申请数量目的
        :param nums:
        :return:
        """
        data = get_all_data(nums)
        # 打乱user_data里边的数据
        # random.shuffle(data)
        # user_data = []
        # for uname in data:
        #     user_data.append(uname)
        return data

    def get_session(self, uname):
        """
        :return:返回登录用户session
        """
        login = PcLogin(uname)
        login.pc_login()
        # self.session = login.get_session()
        return login.get_session()

    def echo_report_pic_addr(self, jid, title):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取响应值类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :param title:活动类型与来源的拼接
        :return:pic_addr
        """
        shikee_cookies = self.session.cookies.get(
            'shikee')  # 获取用户cookies中的shikee部分
        yaml_data = self.yaml.get_data('tmp_shensu_pic_address')
        yaml_data.get('data').update({
            'name': title,
            'Filedata': ('filename', open(os.path.join(image_Path, title), 'rb'), 'image/jpg')
        })
        url = yaml_data.get('url') + '?jid=' + str(jid) + \
            '&act=up&swf_upload_cookie=' + shikee_cookies
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = self.session.post(url, data=m,
                              headers={'Content-Type': m.content_type})
        return json.loads(r.text).get("data")

    def sava_appeal(self,jid, tmp_address):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取响应值类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :param title:活动类型与来源的拼接
        :return:pic_addr
        """
        yaml_data = self.yaml.get_data('shensu')
        yaml_data.get('data').update({
            'img_url': tmp_address,
            'jid': str(jid)
            # 'file': ('filename', open(os.path.join(image_Path, title), 'rb'), 'image/jpg')
            # 'file': ('filename',open(os.path.join(image_Path, '精细报告_真人秀.jpg'), 'rb'), 'image/jpg')
        })
        url = yaml_data.get('url') + '?jid=' + str(jid)
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = self.session.post(url, data=m,
                              headers={'Content-Type': m.content_type})
        print(r.text)
        # return json.loads(r.text).get("data")

    def submit_shensu(self, uname):
        """
        单个提交申诉
        :return:
        """
        self.session = self.get_session(uname)
        statement = """SELECT jid from sk_join WHERE buyer_uname = %s and tid = %s"""
        params = (uname, self.tid)
        value = get_sql_info(statement, params, meta={
            "info": "获取参与jid"
        })
        try:
            jid = value[0].get("jid")
            tmp_address = self.echo_report_pic_addr(jid, '精细报告_真人秀.jpg')
        except:
            pass
        else:
            self.sava_appeal(jid,tmp_address)

    def submit_shensu_more(self, nums):
        """
        批量提交申诉
        :return:
        """
        userdatas = SubmitSS.get_user_data(nums)
        for uname in userdatas:
            self.session = self.get_session(uname)
            statement = """SELECT jid from sk_join WHERE buyer_uname = %s and tid = %s"""
            params = (uname, self.tid)
            value = get_sql_info(statement, params, meta={
                "info": "获取参与jid"
            })
            try:
                jid = value[0].get("jid")
                tmp_address = self.echo_report_pic_addr(jid, '精细报告_真人秀.jpg')
            except:
                pass
            else:
                self.sava_appeal(jid,tmp_address)


def main():
    try:
        tid = int(input(u'请输入活动tid: '))
        status = check_tid(tid)
        if not status:
            raise Exception("活动tid不存在try表，请核实后在重新输入")
    except Exception as e:
        logger.error("reszon => %s" % e)
    else:
        uname = input(u'请输入用户名: ')
        report = SubmitSS(tid)
        report.submit_shensu(uname)


if __name__ == "__main__":
    main()
